package grpc

import (
	"context"
	"fmt"
	"math/rand"
	"rookie-wrapping/rpc/global"
	"rookie-wrapping/rpc/models/dao"
	"rookie-wrapping/rpc/models/services"
	user1 "rookie-wrapping/rpc/proto/user"
	"strconv"
	"time"
)

type UserServer struct {
	user1.UnimplementedRegisterServerServer
}

func (s *UserServer) Register(ctx context.Context, req *user1.RegisterReq) (*user1.RegisterResp, error) {
	user := dao.User{
		Name:    req.Name,
		Mobile:  req.Mobile,
		Address: req.Address,
	}
	err := services.CreateUser(user)
	if err != nil {
		return &user1.RegisterResp{
			Code: 400,
			Msg:  "创建失败",
		}, err
	}
	resp := &user1.RegisterResp{
		Code: 200,
		Msg:  "创建成功",
	}
	return resp, err
}
func (s *UserServer) AddPackage(ctx context.Context, req *user1.AddPackageReq) (*user1.AddPackageResp, error) {
	p := dao.Package{
		Weight:      float64(req.Weight),
		Destination: req.Destination,
		Urgent:      false,
	}
	err := services.CreatePackage(p)
	if err != nil {
		return &user1.AddPackageResp{
			Code: 400,
			Msg:  "创建失败",
		}, err
	}
	resp := &user1.AddPackageResp{
		Code: 200,
		Msg:  "创建成功",
	}
	return resp, err
}

func (s *UserServer) PackageList(ctx context.Context, req *user1.PackageListReq) (*user1.PackageListResp, error) {
	list, err := services.PackageList(req.Destination, int(req.Page), int(req.PageSize))
	if err != nil {
		return &user1.PackageListResp{
			Code: 400,
			Msg:  "列表展示失败",
			Data: nil,
		}, err
	}
	var packageList []*user1.UserInfo
	for _, v := range list {
		packageList = append(packageList, &user1.UserInfo{
			Weight:      float32(v.Weight),
			Destination: v.Destination,
			Urgent:      v.Urgent,
		})
	}
	resp := &user1.PackageListResp{
		Code: 200,
		Msg:  "列表展示成功",
		Data: packageList,
	}
	return resp, err
}

func (s *UserServer) SendSms(ctx context.Context, req *user1.SendSmsReq) (*user1.SendSmsResp, error) {
	num := rand.Intn(9999) + 1000
	code := strconv.Itoa(num)
	key := fmt.Sprintf("login:%s", req.Mobile)
	err := global.RedisClient.Set(key, code, time.Minute*10).Err()
	if err != nil {
		return &user1.SendSmsResp{
			Code: 400,
			Msg:  "缓存失败",
		}, err
	}
	resp := &user1.SendSmsResp{
		Code: 200,
		Msg:  "生成成功",
	}
	return resp, err
}
